/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: HomeFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.main.ui;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.superluo.textbannerlibrary.ITextBannerItemClickListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.kline.ui.KlineTestActivity;
import io.bhex.app.main.adapter.AdsAdapter;
import io.bhex.app.main.bean.ShortcutEntry;
import io.bhex.app.main.presenter.HomePresenter;
import io.bhex.app.market.ui.MarketRankingFragment;
import io.bhex.app.skin.view.SkinTextBannerView;
import io.bhex.app.utils.BasicFunctionsUtil;
import io.bhex.app.utils.CoinUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.ImageLoader.GlideImageLoader;
import io.bhex.app.view.TabEntity;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.sdk.config.bean.BasicFunctionsConfig;
import io.bhex.sdk.config.bean.IndexModuleItem;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.utils.bean.AnnouncementsResponse;
import io.bhex.sdk.utils.bean.BannerResponse;

/**
 * ================================================
 * 描   述：首页
 * ================================================
 */

public class HomeExtFragment extends BaseFragment<HomePresenter, HomePresenter.HomeUI> implements HomePresenter.HomeUI, View.OnClickListener {

    public static final int TAB_BB = 0;
    public static final int TAB_OPTION = 1;
    public static final int TAB_FUTURE = 2;
    private int mPageItemCount;
    private TopBar topBar;
    private Banner banner;
    //    private TextBannerView noticeTx;
    private SkinTextBannerView noticeTx;
    private View homeAdsDeposit;
    private RecyclerView homeAdsRv;
    private View emptyView;
    private AdsAdapter adsAdapter;
    private GridLayoutManager gridLayoutManagerAds;
    private CommonTabLayout tabUpDown;
    private ArrayList<Pair<String, Fragment>> items;
    private int currentTab = TAB_BB;
    private BasicFunctionsConfig basicFunctionsConfig;
    private ViewPager recommendSymbolsVp;
    private MultiplePagerAdapter recommendSymbolsAdapter;
    private List<CoinPairBean> symbolListData = new ArrayList<CoinPairBean>();
    private LinearLayout circyleLayout;
    private TextView leftTextView;
    private View symbolsVpDivider;

    @Override
    protected HomePresenter.HomeUI getUI() {
        return this;
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_layout, null, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @Override
    protected void initViews() {
        super.initViews();
        basicFunctionsConfig = BasicFunctionsUtil.getBasicFunctionsConfig();
        //设置topbar标题
        initSetTopBar();

        SmartRefreshLayout refreshLayout = viewFinder.find(R.id.smartRefresh);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getPresenter().Refresh();
                refreshlayout.finishRefresh(1000/*,false*/);//传入false表示刷新失败
            }
        });

        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        banner = viewFinder.find(R.id.banner);
        noticeTx = viewFinder.find(R.id.notice);
        // noticeTx.setBackgroundColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.color_bg_2_night : R.color.color_bg_2));

        //推荐币种
        recommendSymbolsVp = viewFinder.find(R.id.symbolsVp);
//        recommendSymbolsVp.setOffscreenPageLimit(3);
        //圆点
        circyleLayout = viewFinder.find(R.id.circyle_layout);
        symbolsVpDivider = viewFinder.find(R.id.symbolsVp_divider);

        homeAdsDeposit = viewFinder.find(R.id.home_ads_deposit);
        setAdsDepositLayoutParams(homeAdsDeposit);

//        emptyView = layoutInflater.inflate(R.layout.empty_layout, refreshLayout, false);
//        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
//        layoutParams.height = PixelUtils.dp2px(300);
//        emptyView.setLayoutParams(layoutParams);

        //九宫格快捷入口
        homeAdsRv = viewFinder.find(R.id.home_ads_recyclerview);
        gridLayoutManagerAds = new GridLayoutManager(getActivity(), 4);
        homeAdsRv.setLayoutManager(gridLayoutManagerAds);

        tabUpDown = viewFinder.find(R.id.tab);

        initFragmentTab();

        /*viewFinder.find(R.id.btn_click).setOnClickListener(view -> {
            IntentUtils.startActivity(getContext(),KlineTestActivity.class);
        });*/

//        DebugLog.e("LOCAL::: "+ RateAndLocalManager.GetInstance(getActivity()).getLangLocalConfig(getActivity()));

    }

    /**
     * 初始化设置topBar
     */
    private void initSetTopBar() {
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.getleftImgView().setVisibility(View.GONE);
        leftTextView = topBar.getLeftTextView();
        RelativeLayout.LayoutParams topbarLeftLayout = (RelativeLayout.LayoutParams) leftTextView.getLayoutParams();
        topbarLeftLayout.leftMargin = PixelUtils.dp2px(12);
        leftTextView.setLayoutParams(topbarLeftLayout);
        Drawable iconMy = getResources().getDrawable(R.mipmap.icon_my);
        iconMy.setColorFilter(SkinColorUtil.getDark(this.getContext()), PorterDuff.Mode.SRC_ATOP);
        leftTextView.setCompoundDrawablesWithIntrinsicBounds(null, iconMy, null, null);
        leftTextView.setText(getResources().getString(R.string.title_my));
        leftTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        leftTextView.setGravity(Gravity.CENTER_HORIZONTAL);
        if (CommonUtil.isBhex(getActivity())) {
            topBar.setTitleRightDrawable(R.mipmap.app_header_title);
            topBar.setTitle("");
        } else {
            if (basicFunctionsConfig.isHasHomeHeaderLogo()) {
                topBar.setTitleRightDrawable(R.mipmap.app_header_title);
                topBar.setTitle("");
            } else {
            }
        }
        topBar.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.goAccount(getActivity());

//                testRom();

            }
        });
        topBar.setTitleGravity();
    }

    private void testRom() {
//                boolean isEMUI = RomUtils.isEMUI();
//                boolean isMi = RomUtils.isMIUI();
//                boolean isFlyme = RomUtils.isFlyme();
//                ToastUtils.showLong("isEMUI="+isEMUI +" isMi="+ isMi +"  isFlyme="+isFlyme);
//                DebugLog.e("XXXX","isEMUI="+isEMUI +" isMi="+ isMi +"  isFlyme="+isFlyme);
//
//                ToastUtils.showLong("isEMUI="+RomUtil.isHuaweiRom() +" isMi="+ RomUtil.isMiuiRom() +"  isFlyme="+RomUtil.isFlymeRom(getActivity()));
//                DebugLog.e("XXXX","isEMUI="+RomUtil.isHuaweiRom() +" isMi="+ RomUtil.isMiuiRom() +"  isFlyme="+RomUtil.isFlymeRom(getActivity()));
    }

    @Override
    public void onResume() {
        super.onResume();

        Drawable iconMy = getResources().getDrawable(R.mipmap.icon_my);
        iconMy.setColorFilter(SkinColorUtil.getDark(this.getContext()), PorterDuff.Mode.SRC_ATOP);
        leftTextView.setCompoundDrawablesWithIntrinsicBounds(null, iconMy, null, null);

        reloadNoticeColor();
    }

    private void reloadNoticeColor() {
        try {

            View childView = noticeTx.getChildAt(0);
            if (childView instanceof ViewFlipper) {
                ViewFlipper viewFlipper = (ViewFlipper) childView;
                for (int i = 0; i < viewFlipper.getChildCount(); i++) {
                    TextView childText = (TextView) viewFlipper.getChildAt(i);
                    childText.setTextColor(SkinColorUtil.getDark(getActivity()));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 设置充币布局参数
     *
     * @param homeAdsDeposit
     */
    private void setAdsDepositLayoutParams(View homeAdsDeposit) {
        LinearLayout.LayoutParams homeAdsParams = (LinearLayout.LayoutParams) homeAdsDeposit.getLayoutParams();
        int width = PixelUtils.getScreenWidth() - PixelUtils.dp2px(48);
        homeAdsParams.width = width;
        homeAdsParams.height = width * 64 / 328;
        homeAdsDeposit.setLayoutParams(homeAdsParams);
    }

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    /**
     * 涨跌幅tab
     */
    private void initFragmentTab() {
        BasicFunctionsConfig basicFunctionsConfig = BasicFunctionsUtil.getBasicFunctionsConfig();

        ArrayList<Fragment> fragments = new ArrayList<Fragment>();
        items = new ArrayList<>();
        if (!basicFunctionsConfig.isExchange()) {
            MarketRankingFragment bbMarketRankingFragment = new MarketRankingFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(AppData.INTENT.MARKET_TYPE,AppData.TICKER.MARKET_TYPE_BB);
            bbMarketRankingFragment.setArguments(bundle);
            items.add(new Pair<String, Fragment>(getString(R.string.string_bb), bbMarketRankingFragment));
            fragments.add(bbMarketRankingFragment);
        }
        if (!basicFunctionsConfig.isFuture()) {
            MarketRankingFragment contractMarketRankingFragment = new MarketRankingFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(AppData.INTENT.MARKET_TYPE,AppData.TICKER.MARKET_TYPE_CONTRACT);
            contractMarketRankingFragment.setArguments(bundle);
            items.add(new Pair<String, Fragment>(getString(R.string.string_contract), contractMarketRankingFragment));
            fragments.add(contractMarketRankingFragment);
        }
        if (!basicFunctionsConfig.isOption()) {
            MarketRankingFragment optionMarketRankingFragment = new MarketRankingFragment();
            Bundle bundle = new Bundle();
            bundle.putInt(AppData.INTENT.MARKET_TYPE,AppData.TICKER.MARKET_TYPE_OPTION);
            optionMarketRankingFragment.setArguments(bundle);
            items.add(new Pair<String, Fragment>(getString(R.string.string_option), optionMarketRankingFragment));
            fragments.add(optionMarketRankingFragment);
        }

        if (items.size() > 1) {
            tabUpDown.setVisibility(View.VISIBLE);
            viewFinder.find(R.id.tab_divider).setVisibility(View.VISIBLE);
        } else {
            tabUpDown.setVisibility(View.GONE);
            viewFinder.find(R.id.tab_divider).setVisibility(View.GONE);
        }

        for (Pair<String, Fragment> item : items) {
            mTabEntities.add(new TabEntity(item.first, 0, 0));

        }
//        tabUpDown.setTabData(mTabEntities);
        tabUpDown.setTabData(mTabEntities,this.getActivity(),R.id.fragment_container,fragments);

    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.home_ads_deposit).setOnClickListener(this);

        tabUpDown.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                DebugLog.e("TAB", "onTabSelected  " + position);
                currentTab = position;
            }

            @Override
            public void onTabReselect(int position) {
                DebugLog.e("TAB", "onTabReselect  " + position);
                currentTab = position;
            }
        });

        recommendSymbolsVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                changeCycleDotView(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    @Override
    public int getTab() {
        return currentTab;
    }

    @Override
    protected void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (visible) {
            tabUpDown.setCurrentTab(currentTab);
            noticeTx.startViewAnimator();
        } else {
            noticeTx.stopViewAnimator();
        }
    }

    @Override
    public void showBanner(final List<BannerResponse.BannerBean> bannerList) {
        if (bannerList != null && bannerList.size() > 0) {
            List<String> images = new ArrayList<>();
            final List<String> titles = new ArrayList<>();
            for (BannerResponse.BannerBean bannerBean : bannerList) {
                images.add(bannerBean.getImgUrl());

            }

            //设置banner样式
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            //设置图片加载器
            banner.setImageLoader(new GlideImageLoader());
            //设置图片集合
            banner.setImages(images);
//        banner.update(images);
            //设置banner动画效果
            banner.setBannerAnimation(Transformer.Default);
//        setPagerMargin(banner,10,20,20);
//        try {
//            banner.setPageTransformer(false,ScalePageTransformer.class.newInstance());
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (java.lang.InstantiationException e) {
//            e.printStackTrace();
//        }
            //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
            //设置自动轮播，默认为true
            banner.isAutoPlay(true);
            //设置轮播时间
            banner.setDelayTime(6000);
            //设置指示器位置（当banner模式中有指示器时）
            banner.setIndicatorGravity(BannerConfig.CENTER);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    BannerResponse.BannerBean bannerBean = bannerList.get(position);
                    if (bannerBean.isIsDirect() && !TextUtils.isEmpty(bannerBean.getDirectUrl())) {
                        String directUrl = bannerBean.getDirectUrl();
//                        if (BuildConfig.DEBUG) {
//                            try {
//                                URL url = new URL(directUrl);
//                                String host = url.getHost();
//                                ToastUtils.showShort(UrlsConfig.API_SERVER_URL+ "     "+host);
//                                directUrl = directUrl.replaceAll(host,UrlsConfig.BASIC_URL);
//                            } catch (MalformedURLException e) {
//                                e.printStackTrace();
//                            }
//                        }
                        WebActivity.runActivity(getActivity(), "", directUrl);
                    }

                }
            });
            //banner设置方法全部调用完毕时最后调用
            if (getActivity() != null) {
                banner.start();
            }
        }
    }

    public void setPagerMargin(Banner banner, int margin, int leftMargin, int rightMargin) {
        try {
            Class clazz = Banner.class;
            Field field = clazz.getDeclaredField("viewPager");
            field.setAccessible(true);
            ViewPager viewPager = (ViewPager) field.get(banner);

            // viewPager.setPageMargin(margin);  这句即可实现效果一

            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) viewPager.getLayoutParams();
            params.setMargins(leftMargin, 0, rightMargin, 0);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showAnnounces(final List<AnnouncementsResponse.AnnounceBean> data) {
        if (data != null && data.size() > 0) {
            //设置数据
            List<String> mList = new ArrayList<>();
            for (AnnouncementsResponse.AnnounceBean datum : data) {
                mList.add(datum.getTitle());
            }
            //调用setDatas(List<String>)方法后,TextBannerView自动开始轮播
            //注意：此方法目前只接受List<String>类型
            noticeTx.setDatas(mList);
            reloadNoticeColor();

            //设置TextBannerView点击监听事件，返回点击的data数据, 和position位置
            noticeTx.setItemOnClickListener(new ITextBannerItemClickListener() {
                @Override
                public void onItemClick(String title, int position) {
                    AnnouncementsResponse.AnnounceBean announceBean = data.get(position);
                    if (announceBean != null) {
                        String directUrl = announceBean.getDirectUrl();
                        if (!TextUtils.isEmpty(directUrl)) {
                            WebActivity.runActivity(getActivity(), announceBean.getTitle(), directUrl);
                        }
                    }
                }
            });

        }
    }

    @Override
    public void showNineEntry(ArrayList<IndexModuleItem> data) {
        if (data != null && data.size() > 0) {
            homeAdsRv.setVisibility(View.VISIBLE);
            viewFinder.find(R.id.home_ads_recyclerview_divider).setVisibility(View.VISIBLE);
//        ShortcutEntry.setGridDynamicSpanCountRule(gridLayoutManagerAds,data); //自动适配每行个数
            if (adsAdapter == null) {
                adsAdapter = new AdsAdapter(data);
                adsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        List<IndexModuleItem> data = adapter.getData();
                        ShortcutEntry.handleGoWhere(getActivity(), data, position);
                    }
                });

                homeAdsRv.setAdapter(adsAdapter);
            } else {
                adsAdapter.setNewData(data);
            }
        } else {
            homeAdsRv.setVisibility(View.GONE);
            viewFinder.find(R.id.home_ads_recyclerview_divider).setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_ads_deposit:
                //入金 TODO

                break;
        }
    }

    @Override
    public void showSymbolVp(List<CoinPairBean> listData) {
        if (listData != null && listData.size() > 0) {
            showSymbolVpVisible(true);

            if (recommendSymbolsAdapter == null) {

                recommendSymbolsAdapter = new MultiplePagerAdapter(getContext(), listData,3);
                recommendSymbolsVp.setAdapter(recommendSymbolsAdapter);
                //symbolsVp.addOnPageChangeListener(this);
                createCycleDotView(listData);
            } else {
                recommendSymbolsAdapter.setDataList(listData);
                recommendSymbolsAdapter.notifyDataSetChanged();
                createCycleDotView(listData);
            }
            symbolListData = listData;
        } else {
            showSymbolVpVisible(false);
        }

    }

    @Override
    public void showSymbolVpVisible(boolean isVisible) {
        recommendSymbolsVp.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        circyleLayout.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        symbolsVpDivider.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void showTitleLogo(String defaultIcon) {

    }

    private List<ImageView> cycleDotViews = new ArrayList<>();
    private void createCycleDotView(List<CoinPairBean> listData) {
        cycleDotViews.clear();
        circyleLayout.removeAllViews();
        if (listData != null&&listData.size()>0) {
            if (recommendSymbolsAdapter != null) {
                int pageCount = recommendSymbolsAdapter.getPageCount();
                if (pageCount>1) {
                    circyleLayout.setVisibility(View.VISIBLE);
                    int currentItem = recommendSymbolsVp.getCurrentItem();
//                int pageCount = recommendSymbolsAdapter.getPageCount();
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.leftMargin = PixelUtils.dp2px(8);
                    for (int i = 0; i < pageCount; i++) {
                        ImageView dotView = new ImageView(getActivity());
                        if (i !=0){
                            dotView.setLayoutParams(layoutParams);
                        }
                        if (i == currentItem){
                            dotView.setBackgroundResource(R.mipmap.page_dot_checked);
                        }else{
                            dotView.setBackgroundResource(R.mipmap.page_dot);
                        }
                        cycleDotViews.add(dotView);
                        circyleLayout.addView(dotView);
                    }
                }else{
                    circyleLayout.setVisibility(View.GONE);
                }
            }
        }
    }

    private void changeCycleDotView(int position){
        if(position+1 > cycleDotViews.size()){
            return;
        }
        for (int i = 0; i < cycleDotViews.size(); i++) {

            ImageView dotView = cycleDotViews.get(i);
            if(i == position) {
                dotView.setBackgroundResource(R.mipmap.page_dot_checked);
            }else {
                dotView.setBackgroundResource(R.mipmap.page_dot);
            }
        }
    }

    @Override
    public void changeSymbolVpData(List<TickerBean> datas) {
        if (datas != null && datas.size() > 0) {
            for (TickerBean tickerBean : datas) {
                for (int i = 0; i < symbolListData.size(); i++) {
                    CoinPairBean coinPairBean = symbolListData.get(i);
                    if (coinPairBean.getSymbolId() != null && coinPairBean.getSymbolId().equals(tickerBean.getS())) {
                        coinPairBean.setTicker(tickerBean);

                        //symbolListData.set(i, newBean);
                        if (recommendSymbolsAdapter != null) {
                            recommendSymbolsAdapter.ChangeData(i, coinPairBean);
                        }
                        break;
                    }
                }
            }

            /*if (recommendSymbolsAdapter == null) {
                recommendSymbolsAdapter = new MultiplePagerAdapter(getContext(),symbolListData);
                symbolsVp.setAdapter(recommendSymbolsAdapter);
            }else{
                recommendSymbolsAdapter.mList = symbolListData;
                recommendSymbolsAdapter.notifyDataSetChanged();
            }*/
        }
    }


    public class MultiplePagerAdapter extends PagerAdapter {
        //private List<CoinPairBean> mList = new ArrayList<CoinPairBean>();
        private List<View> mItemViewList = new ArrayList<>();
        private List<View> mPageViewList = new ArrayList<>();
        private LayoutInflater layoutInflater;
        private Context mContext;
        private List<CoinPairBean> mDataList;

        public MultiplePagerAdapter(Context context, List<CoinPairBean> list,int pageItemCount) {
            super();
            mContext = context;
            layoutInflater = LayoutInflater.from(context);
            mPageItemCount = pageItemCount;
            setDataList(list);
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
            return this.mPageViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 页面宽度所占ViewPager测量宽度的权重比例，默认为1
         */
//        @Override
//        public float getPageWidth(int position) {
//            return (float) 1/3;
//        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = (View) object;
            container.removeView(view);
        }

        public void ChangeData(int position, CoinPairBean bean){
            if(position < mItemViewList.size() && bean != null)
                buildView(mItemViewList.get(position), bean);
        }
        public void setDataList( List<CoinPairBean> datalist){
            mDataList = datalist;
            if (datalist == null)
                return;

            int pageViewWidth = PixelUtils.getScreenWidth()-PixelUtils.dp2px(0);

            if (datalist != null && datalist.size()>0) {
                int totalSize = datalist.size();
                //移除多余itemView
                if (mItemViewList.size()>totalSize) {
                    for (int i = mItemViewList.size() - 1; i >= 0; i--) {
                        if (i>totalSize){
                            mItemViewList.remove(i);
                        }else{
                            break;
                        }
                    }
                }

//                int totalPageNeeded = totalSize % mPageItemCount > 0 ? (totalSize/mPageItemCount) + 1 : totalSize/mPageItemCount;
                int totalPageNeeded = getPageCount();
                if (mPageViewList.size() > totalPageNeeded) {
                    for (int i = 0; i < mPageViewList.size(); i++) {
                        if (i>totalPageNeeded) {
                            mPageViewList.remove(i);
                            break;
                        }
                    }
                }

                for (int i = 0; i < datalist.size(); i++) {
                    CoinPairBean coinPairBean = datalist.get(i);
                    int pageNum = i / mPageItemCount ;
                    if (pageNum>=mPageViewList.size()) {
                        if (i%mPageItemCount ==0) {
                            LinearLayout pageView = new LinearLayout(mContext);
                            pageView.setOrientation(LinearLayout.HORIZONTAL);
                            pageView.setVerticalGravity(Gravity.CENTER_VERTICAL);
        //                    ViewPager.LayoutParams layoutParams = new ViewPager.LayoutParams();
        //                    layoutParams.width = pageViewWidth
        //                    pageView.setLayoutParams();

                            mPageViewList.add(pageView);
                        }
                    }

                    LinearLayout currentPageView = (LinearLayout) mPageViewList.get(pageNum);
                    if(i >= mItemViewList.size()){
                        View itemView = layoutInflater.inflate(R.layout.symbols_item_view, null);
                        itemView.setOnClickListener(view -> {
                            IntentUtils.startActivity(getActivity(),KlineTestActivity.class);
                        });
                        LinearLayout.LayoutParams itemViewParams = new LinearLayout.LayoutParams(pageViewWidth/mPageItemCount, ViewGroup.LayoutParams.WRAP_CONTENT);
//                    itemViewParams.width = pageViewWidth/mPageItemCount;
                        itemView.setLayoutParams(itemViewParams);
                        mItemViewList.add(itemView);
                        currentPageView.addView(itemView);
                    }
                    View currentItemView = mItemViewList.get(i);
                    buildView(currentItemView, coinPairBean);

                }

            }else{
                mPageViewList.clear();
                mItemViewList.clear();
            }

        }

        private void buildView(View symbolItem, final CoinPairBean itemModel) {
            if (symbolItem == null || itemModel == null)
                return;
            TickerBean tickerBean = itemModel.getTicker();
            String quoteTokenId = CoinUtils.getQuotePriceUnit(itemModel);
            String symbolStr = CoinUtils.getSymbolName(itemModel);

//            symbolStr = itemModel.getBaseTokenName() + "/" + itemModel.getQuoteTokenName();
//            SpannableStringBuilder builder = new SpannableStringBuilder(symbolStr);
//            ForegroundColorSpan quoteColor = new ForegroundColorSpan(getResources().getColor(R.color.font_color2));
//            builder.setSpan(quoteColor, symbolStr.indexOf("/"), symbolStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            int baseDigit = NumberUtils.calNumerCount(getActivity(), itemModel.getBasePrecision());
            int pricDigit = NumberUtils.calNumerCount(getActivity(), itemModel.getMinPricePrecision());

            /*symbolItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //ToastUtils.showLong("ddd");
                    Log.d("buildView","itemModel=="+itemModel.getBaseTokenName());
                    //IntentUtils.goKline(getActivity(), itemModel);
                    IntentUtils.startActivity(getActivity(), KlineTestActivity.class);
                }
            });*/
            /*symbolItem.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    LogUtil.d("buildView","itemModel=="+itemModel.getBaseTokenName());
                    IntentUtils.goKline(getActivity(), itemModel);
                    return true;
                }
            });*/

            /*((TextView) symbolItem.findViewById(R.id.item_coinpair)).setText(symbolStr);

            if (quoteBean != null) {

                ((TextView) symbolItem.findViewById(R.id.item_amount)).setText(getString(R.string.string_vol) + "  " + NumberUtils.roundFormatDown(quoteBean.getV(), AppData.DIGIT_24H_AMOUNT));
                ((TextView) symbolItem.findViewById(R.id.item_price1)).setText(NumberUtils.roundFormatDown(quoteBean.getC(), pricDigit));
                String legalMoney = RateDataManager.CurRatePrice(quoteTokenId, quoteBean.getC());
                legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
                ((TextView) symbolItem.findViewById(R.id.item_price2)).setText("≈" + legalMoney);

                ((TextView) symbolItem.findViewById(R.id.item_range_ratio)).setText(KlineUtils.calRiseFallRatio(quoteBean.getC(), quoteBean.getO()));
                float riseFallAmount = KlineUtils.calRiseFallAmountFloat(quoteBean.getC(), quoteBean.getO());
                if (riseFallAmount > 0) {
                    ((TextView) symbolItem.findViewById(R.id.item_range_ratio)).setTextColor(ContextCompat.getColor(getActivity(), R.color.green));
                    ((TextView) symbolItem.findViewById(R.id.item_price1)).setTextColor(ContextCompat.getColor(getActivity(), R.color.green));
                } else if (riseFallAmount < 0) {
                    ((TextView) symbolItem.findViewById(R.id.item_range_ratio)).setTextColor(ContextCompat.getColor(getActivity(), R.color.red));
                    ((TextView) symbolItem.findViewById(R.id.item_price1)).setTextColor(ContextCompat.getColor(getActivity(), R.color.red));
                } else {//涨跌幅0默认为涨 显示为绿色
                    ((TextView) symbolItem.findViewById(R.id.item_range_ratio)).setTextColor(ContextCompat.getColor(getActivity(), R.color.green));
                    ((TextView) symbolItem.findViewById(R.id.item_price1)).setTextColor(ContextCompat.getColor(getActivity(), R.color.green));
                }
            } else {
                ((TextView) symbolItem.findViewById(R.id.item_amount)).setText(getString(R.string.string_vol) + "  " + getString(R.string.string_placeholder));
                ((TextView) symbolItem.findViewById(R.id.item_price1)).setText(getString(R.string.string_placeholder));
                ((TextView) symbolItem.findViewById(R.id.item_price2)).setText(getString(R.string.string_placeholder));

                ((TextView) symbolItem.findViewById(R.id.item_range_ratio)).setText(getString(R.string.string_placeholder));
                ((TextView) symbolItem.findViewById(R.id.item_range_ratio)).setTextColor(ContextCompat.getColor(getActivity(), R.color.green));
            }*/

        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View symbolItem = layoutInflater.inflate(R.layout.symbols_item_view, null);

            if(position < mPageViewList.size())
                symbolItem = mPageViewList.get(position);

            container.addView(symbolItem);
            return symbolItem;// 返回填充的View对象
        }

        public int getPageCount() {
            if (mDataList != null && mDataList.size()>0) {
                int totalSize = mDataList.size();
                int totalPageCount =totalSize % mPageItemCount > 0 ? (totalSize/mPageItemCount) + 1 : totalSize/mPageItemCount;
                return totalPageCount;
            }else{
                return 0;
            }
        }

//        @Override
//        public Object instantiateItem(ViewGroup container, int position) {
//            View symbolItem = layoutInflater.inflate(R.layout.symbols_item_view, null);
//            if(position < mItemViewList.size())
//                symbolItem = mItemViewList.get(position);
//
//            container.addView(symbolItem);
//            return symbolItem;// 返回填充的View对象
//        }
    }

}
